<!--
 * @Description: 
 * @Author: wangqi
 * @Date: 2021-05-03 18:01:22
 * @LastEditTime: 2021-05-03 18:20:34
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body></body>

<script>
    let templateStr = `<h2>我买了一个{{thing}}, 花了{{money}}元, 好{{mood}}啊! <h2>`;
    let data = {
        thing: "手机",
        money: 998,
        mood: "开心",
    };

    function render(templateStr, data) {
        // replace 第二个参数为 (findStr, capContext [,capContext1, capContext2, ...] [,str] ) => {};
        // findStr: {{thing}},  正则需要匹配的内容;
        // capContext: thing,   如果存在 () 组的话, 表示的是括号里匹配的内容, 如果存在多个capContext2一次类推;
        // str: <h2>我买了一个....<h2>`, templateStr字符串整体内容;
        return templateStr.replace(/\{\{(\w+)\}\}/g, (findStr, $1) => {
            return data[$1];
        });
    };

    let result = render(templateStr, data);
    console.log(result);
</script>

</html>